//
//  HistoryViewController.m
//  SIPphone
//
//  Created by wrt on 13-10-25.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//

#import "HistoryViewController.h"
#import "AddContactsViewController.h"
#import "CallViewController.h"
#import "AppDelegate.h"
#import "ContactsDateBase.h"
#import "HistoryDataBase.h"
#import "PromptChatDateBase.h"
#import "FriendRespondDateBase.h"
#import "PostMessageDataBase.h"

@interface HistoryViewController ()
{
    NSString *_tempNumber;
}
@end


@implementation HistoryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"history", @"历史记录 History");
        // Custom initialization
    }
    return self;
}

//界面出现时要根据UISegmentedControl的选择来将对应的通话信息存储到数组中。
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
    
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    [historyDB deleteNULLDataWithTime];
    [historyDB deleteExceedData:300];
    
    if (self.segmentControl.selectedIndex == 0)
    {
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [historyDB loadArray:0];
        [self.tableView reloadData];
    }
    else if (self.segmentControl.selectedIndex == 1)
    {
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [historyDB loadArray:1];
        [self.tableView reloadData];
    }
    else if (self.segmentControl.selectedIndex == 2)
    {
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [historyDB loadArray:2];
        [self.tableView reloadData];
    }
    else if (self.segmentControl.selectedIndex == 3)
    {
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [historyDB loadArray:3];
        [self.tableView reloadData];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //删除编辑按钮
    UIBarButtonItem *deleteButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"editor", @"编辑 Editor") style:UIBarButtonItemStyleBordered target:self action:@selector(deleteButtonPressed)];
    self.navigationItem.rightBarButtonItem = deleteButton;
    
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    //用数据库赋值
    [historyDB loadArray:0];
    
    self.segmentControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[NSLocalizedString(@"all", @"全部 All"),NSLocalizedString(@"outgoing", @"去电 Outgoing"),NSLocalizedString(@"incoming", @"来电 incoming"),NSLocalizedString(@"missed", @"未接 Missed")]];
    [self.segmentControl setSelectionIndicatorHeight:3.5f];
    [self.segmentControl setBackgroundColor:[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0]];
    [self.segmentControl setTextColor:[UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0]];
    [self.segmentControl setSelectionIndicatorColor:[UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0]];
    [self.segmentControl setSelectionIndicatorMode:HMSelectionIndicatorFillsSegment];
    [self.segmentControl addTarget:self action:@selector(segamentSelectChanged:) forControlEvents:UIControlEventValueChanged];
    [self.segmentControl setSegmentEdgeInset:UIEdgeInsetsMake(0, 6, 0, 6)];
    [self.segmentControl setFont:[UIFont systemFontOfSize:17.0f]];
    UIBarButtonItem *tempBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.segmentControl];
    UIBarButtonItem *spaceBarbutton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [self.toolBar setItems:@[spaceBarbutton,tempBarButtonItem,spaceBarbutton] animated:YES];
}

//右上角编辑按钮的操作
- (void)deleteButtonPressed
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"取消 cancel") destructiveButtonTitle:NSLocalizedString(@"clear All Records", @"清除全部记录 Clear All Records") otherButtonTitles:NSLocalizedString(@"clear single record", @"清除单个记录 Clear single record"), nil];
    [actionSheet showInView:[UIApplication sharedApplication].keyWindow];  //这么加进去就不会取消按了没反应
}

#pragma mark -
#pragma mark tableViewMethod
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    return historyDB.timeArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    
    BOOL isHaveContacts = NO;
    int tempIndex;
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    ContactsDateBase *contactsDB = [ContactsDateBase shareContactsDataBase];
    for (int i = 0 ; i < contactsDB.userNameArray.count ; i++)
    {
        if ([contactsDB.userNameArray[i] isEqualToString:historyDB.numberArray[indexPath.row]])
        {
            isHaveContacts = YES;
            tempIndex = i;
            break;
        }
    }
    
    if (isHaveContacts == YES)
    {
        cell.textLabel.text = contactsDB.markNameArray[tempIndex];
    }
    else
    {
    cell.textLabel.text = [NSString stringWithFormat:@"%@",historyDB.numberArray[indexPath.row]];
    }
    
    if ([historyDB.statusArray[indexPath.row] isEqualToString:@"拨出"])
    {
        cell.imageView.image = [UIImage imageNamed:@"ic_calllog_outgoing_nomal.png"];
    }
    else if ([historyDB.statusArray[indexPath.row] isEqualToString:@"来电"])
    {
        cell.imageView.image = [UIImage imageNamed:@"ic_calllog_incomming_normal.png"];
    }
    else if ([historyDB.statusArray[indexPath.row] isEqualToString:@"未接"])
    {
        cell.imageView.image = [UIImage imageNamed:@"ic_calllog_missed_normal.png"];
    }
    
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",historyDB.timeArray[indexPath.row]];
    return cell;
}

//编辑模式下可删除的方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    [historyDB deleteWithTime:historyDB.timeArray[indexPath.row]];
    
    //删除掉对应数组内的内容
    [historyDB.numberArray removeObjectAtIndex:indexPath.row];
    [historyDB.timeArray removeObjectAtIndex:indexPath.row];
    [historyDB.statusArray removeObjectAtIndex:indexPath.row];
    [historyDB.displayNameArray removeObjectAtIndex:indexPath.row];
    
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
//选择后会弹出操作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    _tempNumber = [[NSString alloc] init];
    _tempNumber = historyDB.numberArray[indexPath.row];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"please select the operating", @"请选择操作 Please select the operating") message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"return", @"返回 Return") otherButtonTitles:NSLocalizedString(@"call", @"拨打 Call"),NSLocalizedString(@"add contacts", @"添加联系人 Add contacts"), nil];
    [alert show];
}

//UISegmentedControl 的选项被按时的操作
- (IBAction)segamentSelectChanged:(HMSegmentedControl *)segmentedControl
{
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    
    if (segmentedControl.selectedIndex == 0)
    {
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [historyDB loadArray:0];
        [self.tableView reloadData];
    }
    else if (segmentedControl.selectedIndex == 1)
    {
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [historyDB loadArray:1];
        [self.tableView reloadData];
    }
    else if (segmentedControl.selectedIndex == 2)
    {
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [historyDB loadArray:2];
        [self.tableView reloadData];
    }
    else if (segmentedControl.selectedIndex == 3)
    {
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [historyDB loadArray:3];
        [self.tableView reloadData];
    }
}

#pragma mark -
#pragma mark actionSheetMethod
//UIActionSheet 对应按钮的操作
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
        [historyDB removeAlldata];
        [historyDB.timeArray removeAllObjects];
        [historyDB.numberArray removeAllObjects];
        [historyDB.statusArray removeAllObjects];
        [historyDB.displayNameArray removeAllObjects];
        [self.tableView reloadData];
    }
    if (buttonIndex == 1)
    {
        //进入编辑模式
        [self.tableView setEditing:!self.tableView.editing];
    }
    if (buttonIndex == 2)
    {
        
    }
    
}

#pragma mark -
#pragma mark AlertViewMethod
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    if (buttonIndex == 1)//拨打
    {
        //先判断是否是登陆状态，如果不是登陆状态则提示请登陆
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL registerStatus = [defaults boolForKey:@"REGISTERSTATUS"];
        if (registerStatus && _tempNumber.length > 1)
        {
            SIPInterface *interface = [SIPInterface shareSIPInterface];
            [interface start_Call:_tempNumber];
            [historyDB writeIntoDatabaseWithNumber:_tempNumber andDisplayName:_tempNumber];
        }
        else if(!registerStatus)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"please log in", @"请先登陆 Please log in") delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
            [alert show];
            [alert dismissWithClickedButtonIndex:0 animated:YES];
        }
    }
    else if (buttonIndex == 2)//添加联系人
    {
        AddContactsViewController *addContactsVC = [[AddContactsViewController alloc] initWithNumber:_tempNumber];
        [self.navigationController pushViewController:addContactsVC animated:YES];
    }
}

#pragma mark -
#pragma mark SIPlistenMethod
- (void)outgoingCallBegin  //主动呼叫开始
{
    dispatch_async(dispatch_get_main_queue(),^{
        CallViewController *callVC = [[CallViewController alloc] initWithNumber:_tempNumber];
        callVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self presentModalViewController:callVC animated:YES];
    });
}

- (void)registerSuccessful //注册成功时的操作
{
    dispatch_async(dispatch_get_main_queue(),^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ALERTVIEWCLOSEED" object:nil];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:YES forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
    });
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (app.isFristOpen == 1)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //个人状态 设置在线
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface setMyStatusWithInt:1];
        [defaults setInteger:1 forKey:@"SAVEMYSTATUS"];
        app.isFristOpen++;
        
        NSString *userName = [[NSString alloc] init];
        userName = [defaults valueForKey:@"SAVEUSERNAME"];
        //创建用于存储联系人的数据库
        ContactsDateBase *contactsDb = [ContactsDateBase shareContactsDataBase];
        [contactsDb changeTableName:userName];
        [contactsDb creatDB];
        [contactsDb readDB];
        
        //创建用于存储好友信息的数据库
        FriendRespondDateBase *friendRespondDB = [FriendRespondDateBase shareFriendRespondDateBase];
        [friendRespondDB changeTableName:userName];
        [friendRespondDB creatDB];
        [friendRespondDB readDB];
        
        //创建用于即时聊天的数据库
        PromptChatDateBase *promptDB = [PromptChatDateBase sharePromptChatDB];
        [promptDB changeTableName:userName];
        [promptDB creatDB];
        [promptDB readDB];
        
        //创建用于历史记录的数据库
        HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
        [historyDB changeTableName:userName];
        [historyDB createDb];
        [historyDB loadArray:0];
        
        //创建用于推送消息的数据库
        PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
        [postMsgDB changeTableName:userName];
        [postMsgDB createDb];
        [postMsgDB loadArray];
        
//        NSMutableArray *tempUserNameArray = [[NSMutableArray alloc] init];
//        NSMutableArray *tempIpArray = [[NSMutableArray alloc] init];
        
        //将列表中的好友传到底层去
//        for (int i = 0; i < contactsDb.isFriendArray.count; i++)
//        {
//            if ([contactsDb.isFriendArray[i] isEqualToString:@"好的"])
//            {
//                [tempUserNameArray addObject:contactsDb.userNameArray[i]];
//                [tempIpArray addObject:contactsDb.ipPortArray[i]];
//            }
//        }
//        
//        for (int j = 0; j < tempUserNameArray.count; j++)
//        {
//            SIPInterface *interface = [SIPInterface shareSIPInterface];
//            [interface addFriendsWithUserName:tempUserNameArray[j] andDisPlayName:@"" andIp:tempIpArray[j]];
//        }
    }
}

- (void)registerFailed  //注册失败时的操作
{
    dispatch_async(dispatch_get_main_queue(),^{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:NO forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
    });
}

- (void)openWindow
{
    
}
- (void)callEnding
{
    
}
- (void)callAnswer
{
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
